<template>
  <div>
    <div v-if="parkingData.length">
      <div class="image-container">
        <div v-for="parkingElement in parkingData" :key="parkingElement.id" class="image-item"
          @click="openLightbox(getImageUrl(parkingElement.img_path))">
          <img v-if="parkingElement.img_path" :src="getImageUrl(parkingElement.img_path)" />
        </div>
      </div>
    </div>
    <p v-else>{{ $t("ui.photoList.noImages") }}</p>

    <a-modal v-model:visible="isLightboxVisible" footer="" @cancel="closeLightbox" closable :width="'90%'" :style="{
      top: '10px',
      maxHeight: '95vh',
      height: '95vh',
      overflowY: 'false',
    }">
      <img :src="currentImage" class="lightbox-image" />
    </a-modal>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  onMounted,
  computed,
  watch,
  onBeforeUnmount,
} from "vue";
import axios from "axios";
import { CameraEvent } from "@/types/types"; // 导入 ApifoxModel 类型
import { useStore } from "vuex";
import { Modal } from "ant-design-vue";

export default defineComponent({
  name: "PhotoList",
  components: {
    "a-modal": Modal,
    // "a-pagination": Pagination,
  },
  setup(props, { emit }) {
    const store = useStore();
    // const events = ref<any[]>([]); // 存储事件数据
    const parkingData = ref<CameraEvent[]>([]);
    // const page = ref(1); // 当前页码
    // const pageSize = 10; // 每页显示的条数
    const isLightboxVisible = ref(false); // 控制 Lightbox 显示的状态
    // const isPlaceholderVisible = ref(true); // 控制占位符可见性
    const currentImage = ref(""); // 当前放大的图片 URL
    let fetchInterval: ReturnType<typeof setInterval>; // 用于存储 setInterval 的返回值
    const fetchEvents = async () => {
      // 从store获取selectedVideo
      const selectedVideo = computed(() => store.getters.getSelectedVideo);
      // 获取 cameraId
      const cameraId = selectedVideo.value?.camera_id; // 从 selectedVideo 中获取 camera_id
      // 获取当前时间
      const currentTime = new Date().toLocaleString(); // 获取当前时间字符串
      console.log(
        `当前时间: ${currentTime}, cameraId = ${cameraId}, name = ${selectedVideo.value?.camera_name}`
      );
      // if (selectedVideo.value?.camera_name === "王庄") {
      //   const response = await axios.get("/mock/parkingList");
      //   parkingData.value = response.data.data.data;
      // } else {
      //   const response = await axios.get("/mock/parkingList2");
      //   parkingData.value = response.data.data.data;
      // }
      // 请求数据的 URL
      try {
        const response = await axios.get("http://172.30.45.98:8080/events?", {
          params: {
            parking: selectedVideo.value?.camera_name,
            page: 1, // 当前页码
            size: 10, // 每页条目数
          },
        });

        // // 提取 data 域
        parkingData.value = response.data.data;
      } catch (error) {
        console.error("获取照片数据时发生错误:", error);
      }
    };

    const getImageUrl = (imagePath: string) => {
      const baseUrl =
        "https://36.248.25.143:31216/api/aisp-storage-center/v1/files?path=";
      const encodedPath = encodeURIComponent(imagePath);
      // console.log(
      //   `imagePath = ${imagePath}, 图片地址: ${baseUrl + encodedPath}`
      // );
      return baseUrl + encodedPath; // 构建完整的图片 URL
    };

    const openLightbox = (imageUrl: string) => {
      currentImage.value = imageUrl; // 设置当前图片 URL
      emit("open-lightbox"); // 发出事件，通知父组件显示占位符
      // 显示大图片
      setTimeout(() => {
        isLightboxVisible.value = true; // 显示大图
      }, 100); // 确保占位符显示后再显示大图
    };

    const closeLightbox = () => {
      isLightboxVisible.value = false; // 隐藏大图片
      emit("close-lightbox"); // 发出事件，通知父组件隐藏占位符
      currentImage.value = ""; // 清空当前图片 URL
    };

    const startFetchInterval = () => {
      fetchInterval = setInterval(() => {
        fetchEvents();
      }, 5000); // 每5秒请求一次
    };

    const stopFetchInterval = () => {
      clearInterval(fetchInterval); // 清除定时器
    };

    onMounted(() => {
      console.log("启动PhotoList的初次mount::fetchEvents");
      fetchEvents(); // 组件挂载时调用函数获取数据
      startFetchInterval(); // 启动定时请求
    });

    // 监听 selectedVideo.camera_name 的变化
    watch(
      () => store.getters.getSelectedVideo?.camera_name,
      (newName, oldName) => {
        if (newName !== oldName) {
          console.log(`Camera Name changed from ${oldName} to ${newName}`);
          stopFetchInterval(); // 停止旧的请求
          fetchEvents(); // 立即请求一次新的数据
          startFetchInterval(); // 启动新的定时请求
        }
      }
    );

    // 组件卸载时清除定时器
    const stopPolling = () => {
      if (fetchInterval) {
        clearInterval(fetchInterval);
      }
    };

    // 在组件卸载时调用清理函数
    onBeforeUnmount(stopPolling);

    return {
      parkingData,
      getImageUrl,
      isLightboxVisible,
      currentImage,
      openLightbox,
      closeLightbox,
    };
  },
});
</script>

<style scoped>
.image-container {
  display: flex;
  overflow-x: auto;
  /* 允许横向滚动 */
  white-space: nowrap;
  /* 防止换行 */
  padding: 10px;
  /* 可选：增加内边距 */
}

.image-item {
  flex: 0 0 9%;
  /* 每个图片占屏幕宽度的10% */
  margin-right: 8px;
  /* 每个图片之间的间距 */
  cursor: pointer;
  /* 鼠标悬停时变为手形光标 */
}

img {
  width: 100%;
  /* 图片宽度占满父元素 */
  height: auto;
  /* 保持图片比例 */
}

.lightbox-image {
  max-width: 90%;
  /* 最大宽度为页面的99% */
  max-height: 90%;
  /* 最大高度为页面的90% */
}

.modal-content {
  display: flex;
  /* 使用 Flexbox 布局 */
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
  height: 100%;
  /* 使内容区域高度占满模态框 */
}

.lightbox-image {
  max-width: 100%;
  /* 图片最大宽度为模态框的100% */
  max-height: 90vh;
  /* 图片最大高度为视口高度的80% */
  object-fit: contain;
  /* 保持图片比例 */
}
</style>
